package net.sk.china.city.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sk.china.city.utils.DateUtils;
import net.sk.china.city.utils.SecurityUtils;
import net.sk.china.common.exception.ServiceException;
import net.sk.china.city.utils.PlatformIdHolder;
import lombok.SneakyThrows;
import net.sk.china.city.domain.*;
import net.sk.china.city.domain.dto.donate.DonateSourceDTO;
import net.sk.china.city.domain.vo.*;
import net.sk.china.city.mapper.*;
import net.sk.china.city.service.IArSupermarketProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 超市商品管理Service业务层处理
 *
 * @author gxf'
 * @date 2024-03-27
 */
@Service
public class ArSupermarketProductServiceImpl implements IArSupermarketProductService {
    @Autowired
    private ArSupermarketProductMapper arSupermarketProductMapper;

    @Autowired
    private ArProductDetailsMapper arProductDetailsMapper;

    @Autowired
    private ArInventoryMapper arInventoryMapper;

    @Autowired
    private ArSupermarketCategoryMapper supermarketCategoryMapper;

    @Autowired
    private ArDonateSourceMapper arDonateSourceMapper;

    /**
     * 查询超市商品管理
     *
     * @param id 超市商品管理主键
     * @return 超市商品管理
     */
    @SneakyThrows
    @Override
    public SupermarketProductInfoVO selectArSupermarketProductById(Long id) {
        List<ArInventory> arInventories = arInventoryMapper.selectList(new QueryWrapper<ArInventory>().eq("product_id", id));
        SupermarketProductInfoVO supermarketProductInfoVO = arSupermarketProductMapper.selectArSupermarketProductById(id);
        ArSupermarketCategory arSupermarketCategory = supermarketCategoryMapper.selectById(supermarketProductInfoVO.getCategoryId());
        List<Long> dataList = new ObjectMapper().readValue(supermarketProductInfoVO.getSourceId(), new TypeReference<List<Long>>() {
        });
        List<DonateSourceDTO> arDonateSources = new ArrayList<>();
        for (Long sourceId : dataList) {
            ArDonateSource arDonateSource = arDonateSourceMapper.selectById(sourceId);
            DonateSourceDTO donateSource = new DonateSourceDTO();
            donateSource.setId(arDonateSource.getId());
            donateSource.setDonateName(arDonateSource.getDonateName());
            arDonateSources.add(donateSource);
        }
        supermarketProductInfoVO.setDonateSourceDTOS(arDonateSources);
        supermarketProductInfoVO.setCategoryName(arSupermarketCategory.getCategoryName());
        supermarketProductInfoVO.setKind(arSupermarketCategory.getKind());
        supermarketProductInfoVO.setInventories(arInventories);
        return supermarketProductInfoVO;
    }

    /**
     * 查询超市商品管理列表
     *
     * @param arSupermarketProduct 超市商品管理
     * @return 超市商品管理
     */
    @Override
    public List<SupermarketProductVO> selectArSupermarketProductList(ArSupermarketProduct arSupermarketProduct) {
        arSupermarketProduct.setPlatformId(PlatformIdHolder.getPlatformId());
        return arSupermarketProductMapper.selectArSupermarketProductList(arSupermarketProduct);
    }

    /**
     * 新增超市商品管理
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int insertArSupermarketProduct(AddSupermarketProductVO addSupermarketProductVO) {
        if (addSupermarketProductVO.getInventories().isEmpty()) {
            throw new ServiceException("库存信息不能为空", 409);
        }
        if(addSupermarketProductVO.getDonateSourceDTOS().isEmpty()){
            throw new ServiceException("捐赠来源不能为空", 409);
        }
        ArProductDetails arProductDetails = new ArProductDetails();
        arProductDetails.setSellByDate(addSupermarketProductVO.getSellByDate());
        arProductDetails.setBrand(addSupermarketProductVO.getBrand());
        arProductDetails.setStyle(addSupermarketProductVO.getStyle());
        arProductDetails.setFunctionality(addSupermarketProductVO.getFunctionality());
        arProductDetails.setServiceIntroduce(addSupermarketProductVO.getServiceIntroduce());
        arProductDetails.setImgUrl(JSON.toJSONString(addSupermarketProductVO.getImgUrl()));
        int i = arProductDetailsMapper.insertArProductDetails(arProductDetails);
        if (i <= 0) {
            throw new ServiceException("新增失败", 409);
        }
        List<DonateSourceDTO> arDonateSources = addSupermarketProductVO.getDonateSourceDTOS();
        List<String> sourceId = new ArrayList<>();
        if (arDonateSources != null) {
            for (DonateSourceDTO donateSourceDTO : arDonateSources) {
                sourceId.add(donateSourceDTO.getId().toString());
            }
        }
        ArSupermarketProduct arSupermarketProduct = new ArSupermarketProduct();
        arSupermarketProduct.setIndexImg(addSupermarketProductVO.getIndexImg());
        arSupermarketProduct.setProductName(addSupermarketProductVO.getProductName());
        arSupermarketProduct.setReleaseTime(addSupermarketProductVO.getReleaseTime());
        arSupermarketProduct.setProductStatus(addSupermarketProductVO.getProductStatus());
        arSupermarketProduct.setDetailsId(arProductDetails.getId());
        arSupermarketProduct.setSalesVolume(0);
        arSupermarketProduct.setSourceId(JSON.toJSONString(sourceId));
        arSupermarketProduct.setCategoryId(addSupermarketProductVO.getCategoryId());
        arSupermarketProduct.setLocationId(addSupermarketProductVO.getLocationId());
        arSupermarketProduct.setCreateTime(LocalDate.now());
        arSupermarketProduct.setCreateBy(SecurityUtils.getUsername());
        arSupermarketProduct.setPlatformId(PlatformIdHolder.getPlatformId());
        int i1 = arSupermarketProductMapper.insertArSupermarketProduct(arSupermarketProduct);
        if (i1 <= 0) {
            throw new ServiceException("新增失败", 409);
        }
        int totalInventory = 0;
        for (ArInventory arInventory : addSupermarketProductVO.getInventories()) {
            ArInventory add = new ArInventory();
            add.setProductName(addSupermarketProductVO.getProductName());
            add.setProCode(arInventory.getProCode());
            add.setColor(arInventory.getColor());
            add.setInventory(arInventory.getInventory());
            add.setSize(arInventory.getSize());
            add.setSpecifications(arInventory.getSpecifications());
            add.setTimeSlot(arInventory.getTimeSlot());
            add.setTimeInterval(arInventory.getTimeInterval());
            add.setProductId(arSupermarketProduct.getId());
            add.setIntegratedWorth(arInventory.getIntegratedWorth());
            add.setSourceId(JSON.toJSONString(sourceId));
            int insert = arInventoryMapper.insert(add);
            if (insert <= 0) {
                throw new ServiceException("新增失败", 409);
            }
            totalInventory += arInventory.getInventory();
        }
        BigDecimal minIntegratedWorth = addSupermarketProductVO.getInventories().stream()
                .map(arInventory -> arInventory.getIntegratedWorth())
                .reduce(BigDecimal::min)
                .orElse(BigDecimal.ZERO);
        ArSupermarketProduct update = new ArSupermarketProduct();
        update.setId(arSupermarketProduct.getId());
        update.setInventory(totalInventory);
        update.setIntegratedWorth(minIntegratedWorth);
        int i2 = arSupermarketProductMapper.updateArSupermarketProduct(update);
        if (i2 <= 0) {
            throw new ServiceException("新增失败", 409);
        }
        return 1;
    }

    /**
     * 修改超市商品管理
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int updateArSupermarketProduct(UpdateSupermarketProductVO updateSupermarketProductVO) {
        if (updateSupermarketProductVO.getInventories().isEmpty()) {
            throw new ServiceException("库存信息不能为空", 409);
        }
        if(updateSupermarketProductVO.getDonateSourceDTOS().isEmpty()){
            throw new ServiceException("捐赠来源不能为空", 409);
        }
        List<DonateSourceDTO> arDonateSources = updateSupermarketProductVO.getDonateSourceDTOS();
        List<String> sourceId = new ArrayList<>();
        if (arDonateSources != null) {
            for (DonateSourceDTO donateSourceDTO : arDonateSources) {
                sourceId.add(donateSourceDTO.getId().toString());
            }
        }
        int totalInventory = 0;
        for (ArInventory arInventory : updateSupermarketProductVO.getInventories()) {
            ArInventory update = new ArInventory();
            update.setProductName(updateSupermarketProductVO.getProductName());
            update.setProCode(arInventory.getProCode());
            update.setSize(arInventory.getSize());
            update.setColor(arInventory.getColor());
            update.setProductId(updateSupermarketProductVO.getId());
            update.setSpecifications(arInventory.getSpecifications());
            update.setTimeSlot(arInventory.getTimeSlot());
            update.setTimeInterval(arInventory.getTimeInterval());
            update.setInventory(arInventory.getInventory());
            update.setIntegratedWorth(arInventory.getIntegratedWorth());
            update.setSourceId(JSON.toJSONString(sourceId));
            if (arInventory.getId() != null) {
                update.setId(arInventory.getId());
                int i = arInventoryMapper.updateById(update);
                if (i <= 0) {
                    throw new ServiceException("修改失败", 409);
                }
            } else {
                int i = arInventoryMapper.insert(update);
                if (i <= 0) {
                    throw new ServiceException("修改失败", 409);
                }
            }

            totalInventory += arInventory.getInventory();
        }
        BigDecimal minIntegratedWorth = updateSupermarketProductVO.getInventories().stream()
                .map(arInventory -> arInventory.getIntegratedWorth())
                .reduce(BigDecimal::min)
                .orElse(BigDecimal.ZERO);
        ArSupermarketProduct arSupermarketProduct = new ArSupermarketProduct();
        arSupermarketProduct.setId(updateSupermarketProductVO.getId());
        arSupermarketProduct.setIndexImg(updateSupermarketProductVO.getIndexImg());
        arSupermarketProduct.setProductName(updateSupermarketProductVO.getProductName());
        arSupermarketProduct.setReleaseTime(updateSupermarketProductVO.getReleaseTime());
        arSupermarketProduct.setProductStatus(updateSupermarketProductVO.getProductStatus());
        arSupermarketProduct.setInventory(totalInventory);
        arSupermarketProduct.setIntegratedWorth(minIntegratedWorth);
        arSupermarketProduct.setSourceId(JSON.toJSONString(sourceId));
        arSupermarketProduct.setCategoryId(updateSupermarketProductVO.getCategoryId());
        arSupermarketProduct.setLocationId(updateSupermarketProductVO.getLocationId());
        arSupermarketProduct.setUpdateTime(LocalDate.now());
        arSupermarketProduct.setUpdateBy(SecurityUtils.getUsername());
        int i = arSupermarketProductMapper.updateArSupermarketProduct(arSupermarketProduct);
        if (i <= 0) {
            throw new ServiceException("修改失败", 409);
        }
        ArProductDetails arProductDetails = new ArProductDetails();
        arProductDetails.setId(updateSupermarketProductVO.getDetailsId());
        arProductDetails.setSellByDate(updateSupermarketProductVO.getSellByDate());
        arProductDetails.setBrand(updateSupermarketProductVO.getBrand());
        arProductDetails.setStyle(updateSupermarketProductVO.getStyle());
        arProductDetails.setFunctionality(updateSupermarketProductVO.getFunctionality());
        arProductDetails.setServiceIntroduce(updateSupermarketProductVO.getServiceIntroduce());
        // todo 删除不存在的图片
        arProductDetails.setImgUrl(JSON.toJSONString(updateSupermarketProductVO.getImgUrl()));
        int i1 = arProductDetailsMapper.updateArProductDetails(arProductDetails);
        if (i1 <= 0) {
            throw new ServiceException("修改失败", 409);
        }
        return 1;
    }

    /**
     * 批量删除超市商品管理
     *
     * @param ids 需要删除的超市商品管理主键
     * @return 结果
     */
    @Override
    public int deleteArSupermarketProductByIds(Long[] ids)
    {
//        return arSupermarketProductMapper.deleteArSupermarketProductByIds(ids);
        for (Long id : ids){
            ArSupermarketProduct arSupermarketProduct = new ArSupermarketProduct();
            arSupermarketProduct.setId(id);
            arSupermarketProduct.setDelFlag("2");
            int i = arSupermarketProductMapper.updateById(arSupermarketProduct);
            if (i <= 0) {
                throw new ServiceException("删除失败", 409);
            }
        }
        return 1;
    }

    /**
     * 删除超市商品管理信息
     *
     * @param id 超市商品管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteArSupermarketProductById(Long id) {
        ArSupermarketProduct arSupermarketProduct = new ArSupermarketProduct();
        arSupermarketProduct.setId(id);
        arSupermarketProduct.setDelFlag("2");
        int i = arSupermarketProductMapper.updateById(arSupermarketProduct);
        if (i <= 0) {
            throw new ServiceException("删除失败", 409);
        }
//        int i = arProductDetailsMapper.deleteById(arSupermarketProductMapper.selectById(id).getDetailsId());
//        if(i <=0 ){
//            throw new ServiceException("删除失败",409);
//        }
//        int i1 = arInventoryMapper.delete(new QueryWrapper<ArInventory>().eq("product_id", id));
//        if(i1 <=0 ){
//            throw new ServiceException("删除失败",409);
//        }
//        int i2 = arSupermarketProductMapper.deleteById(id);
//        if(i2 <=0 ){
//            throw new ServiceException("删除失败",409);
//        }
        return 1;
    }

    @Override
    public int updateStatus(ArSupermarketProduct arSupermarketProduct) {
        ArSupermarketProduct supermarketProduct = new ArSupermarketProduct();
        supermarketProduct.setId(arSupermarketProduct.getId());
        supermarketProduct.setProductStatus(arSupermarketProduct.getProductStatus());
        supermarketProduct.setUpdateTime(LocalDate.now());
        supermarketProduct.setUpdateBy(SecurityUtils.getUsername());
        int i = arSupermarketProductMapper.updateArSupermarketProduct(supermarketProduct);
        if (i <= 0) {
            throw new ServiceException("修改失败", 409);
        }
        return i;
    }

    @Override
    public int deleteInventory(Long inventoryId) {
        int i = arInventoryMapper.deleteById(inventoryId);
        if (i <= 0) {
            throw new ServiceException("删除失败", 409);
        }
        return i;
    }

    /**
     * 根据商品编码查询库存
     *
     * @param proCode
     * @return
     */
    @Override
    public ArInventoryVO getSupermarketProductByProCode(String proCode) {
        ArInventory arInventory = arInventoryMapper.selectOne(new QueryWrapper<ArInventory>().eq("pro_code", proCode).isNull("inventory_flag"));
        if (arInventory==null)
            throw new ServiceException("商品不存在",409);
        if (arInventory.getInventory() < 1)
            throw new ServiceException("该商品库存不足");
        ArInventoryVO arInventoryVO = new ArInventoryVO();
        BeanUtils.copyProperties(arInventory, arInventoryVO);
        String size = arInventory.getSize();
        String color = arInventory.getColor();
        String specifications = arInventory.getSpecifications();

        arInventoryVO.setSpecification(color,size,specifications);
        return arInventoryVO;
    }
}
